package com.btpn.custody.web.m003.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;

import com.btpn.custody.bean.ParameterBeans;
import com.btpn.custody.common.Constant;
import com.btpn.custody.dao.IAccount;
import com.btpn.custody.dao.IArea;
import com.btpn.custody.dao.IBranch;
import com.btpn.custody.dao.IUser;
import com.btpn.custody.entity.Area;
import com.btpn.custody.entity.Branch;
import com.btpn.custody.entity.User;
import com.btpn.custody.web.m003.model.Report02Model;
import com.btpn.infra.utils.MyCollectionUtils;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.validator.annotations.IntRangeFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;

@ParentPackage(value="custody")
@Results({
	@Result(name="input", location="t_report02_form")
})
@Validations(
	intRangeFields = {
		@IntRangeFieldValidator(type = ValidatorType.SIMPLE, fieldName = "selectedMonth", min = "1", max = "12", message = "Pilih bulan"),
		@IntRangeFieldValidator(type = ValidatorType.SIMPLE, fieldName = "selectedYear", min = "1958", max = "2020", message = "Pilih tahun")
	}
)
public class Jasper02Action extends ActionSupport implements Preparable {

	/*=============================================== C O N S T A N T =========================================*/
	private static final long serialVersionUID = 1532302098186868740L;

	/*=============================================== M E M B E R =============================================*/
	@Autowired
	private IAccount accountDaoHibernate;
	
	@Autowired
	private IArea areaDaoHibernate;
	
	@Autowired
	private IBranch branchDaoHibernate;
	
	@Autowired
	private IUser userDaoHibernate;
	
	@Autowired
	private ParameterBeans parameterBeans;
	
	private String jakarta;
	private Map<String, String> areaMap;
	
	private List<Report02Model> report02Models;
	private Map<String, Object> paramMap;
	
	private Long areaId;
	private Integer selectedMonth;
	private String[] years = new String[] {
			"1958", "1959", "1960", "1961", "1962", "1963", "1964", "1965", "1966", 
			"1967", "1968", "1969", "1970", "1971", "1972", "1973", "1974", "1975", "1976", 
			"1977", "1978", "1979", "1980", "1981", "1982", "1983", "1984", "1985", "1986", 
			"1987", "1988", "1989", "1990", "1991", "1992", "1993", "1994", "1995", "1996", 
			"1997", "1998", "1999", "2000", "2001", "2002", "2003", "2004", "2005", "2006", 
			"2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", 
			"2017", "2018", "2019", "2020" };
	private Integer selectedYear;
	
	/*=============================================== B E H A V I O R =========================================*/
	@SuppressWarnings("unchecked")
	public void init() {
		User user = userDaoHibernate.get(SecurityContextHolder.getContext().getAuthentication().getName());
		
		// if user jakarta
		if (user.getArea().isJakarta()) {
			jakarta = "1";
			areaMap = parameterBeans.getmArea();			
		} else {
			jakarta = "-1";
			areaMap = new HashMap<String, String>();
			for (Area a : areaDaoHibernate.findInRegion(user.getArea().getRegion().getId())) {
//				System.out.println("-"+a.getId()+a.getName());
				areaMap.put(a.getId().toString(), a.getName());
			}
			areaMap = MyCollectionUtils.sortByComparator(areaMap);
		}
	}

	@SkipValidation
	@Action(value = "/report02-form", results = { @Result(name="success", location="t_report02_form") })
	public String execute() throws Exception {
		
		return SUCCESS;
	}

	@Action(value = "/report02", results = { 
			@Result(name="success", type="jasper", 
					params = { 	"location", "/jasper/report02.jasper", 
								"dataSource", "report02Models", 
								"reportParameters", "paramMap", 
								"contentDisposition", "attachment", 
								"format", "PDF", 
								"documentName", "SLA Summary"}) 
	})
	public String showReport02() throws Exception {

		User user = userDaoHibernate.get(SecurityContextHolder.getContext().getAuthentication().getName());
		
		Long a=0l, b=0l;
		// check for need to show MASTER chart
		if (jakarta.equals("1")) {			// jakarta
			if (areaId == -1) {				// areaId==-1
				a = accountDaoHibernate.countForAccuracyAllSLA(Constant.STATUS__ON_TIME, selectedMonth, selectedYear);
				b = accountDaoHibernate.countForAccuracyAllSLA(Constant.STATUS__OUT_OF_DATE, selectedMonth, selectedYear);
			} else {
				a = accountDaoHibernate.countForAccuracyMasterSLA(areaId, Constant.STATUS__ON_TIME, selectedMonth, selectedYear);
				b = accountDaoHibernate.countForAccuracyMasterSLA(areaId, Constant.STATUS__OUT_OF_DATE, selectedMonth, selectedYear);
			}
		} else {							// non-jakarta : based on areaId user
			a = accountDaoHibernate.countForAccuracyMasterSLA(user.getArea().getId(), Constant.STATUS__ON_TIME, selectedMonth, selectedYear);
			b = accountDaoHibernate.countForAccuracyMasterSLA(user.getArea().getId(), Constant.STATUS__OUT_OF_DATE, selectedMonth, selectedYear);
		}

		paramMap = new HashMap<String, Object>(0);
		paramMap.put("monthName", 	Constant.monthName[selectedMonth]);
		paramMap.put("year", 		selectedYear);
		
		if ((a==0) & (b==0)) {
			paramMap.put("isShowChart", Boolean.FALSE);
		} else {
			paramMap.put("isShowChart", Boolean.TRUE);
			
			// report master : areaId, month, year, & status			
			paramMap.put("master_onTime", 	a);
			paramMap.put("master_late", 	b);
		}
		
		// init Report02Models
		report02Models = new ArrayList<Report02Model>(0);
		
		if (jakarta.equals("1")) {			// jakarta
			if (areaId == -1) {			// areaId==null
				// count for each branch
				for (Branch branch : branchDaoHibernate.findAll()) {
					Long onTime = accountDaoHibernate.countForAccuracyDetailSLA(branch.getId(), Constant.STATUS__ON_TIME, selectedMonth, selectedYear);
					Long late = accountDaoHibernate.countForAccuracyDetailSLA(branch.getId(), Constant.STATUS__OUT_OF_DATE, selectedMonth, selectedYear);
					
					if ((onTime!=0) | (late!=0)) {
						report02Models.add(new Report02Model(branch.getName(), onTime, late));
					}			
				} 
			} else {						// areaId!=null
				// count for each branch
				for (Branch branch : branchDaoHibernate.findByAreaId(areaId)) {
					Long onTime = accountDaoHibernate.countForAccuracyDetailSLA(branch.getId(), Constant.STATUS__ON_TIME, selectedMonth, selectedYear);
					Long late = accountDaoHibernate.countForAccuracyDetailSLA(branch.getId(), Constant.STATUS__OUT_OF_DATE, selectedMonth, selectedYear);
					
					if ((onTime!=0) | (late!=0)) {
						report02Models.add(new Report02Model(branch.getName(), onTime, late));
					}			
				}
			}
		} else {												// (non-jakarta)
			// count for each branch
			for (Branch branch : branchDaoHibernate.findByAreaId(user.getArea().getId())) {
				Long onTime = accountDaoHibernate.countForAccuracyDetailSLA(branch.getId(), Constant.STATUS__ON_TIME, selectedMonth, selectedYear);
				Long late = accountDaoHibernate.countForAccuracyDetailSLA(branch.getId(), Constant.STATUS__OUT_OF_DATE, selectedMonth, selectedYear);
				
				if ((onTime!=0) | (late!=0)) {
					report02Models.add(new Report02Model(branch.getName(), onTime, late));
				}			
			}  
		}
		
		return SUCCESS;
	}
	
	/*=============================================== G E T T E R   &   S E T T E R ===========================*/
	public Integer getSelectedMonth() {
		return selectedMonth;
	}

	public void setSelectedMonth(Integer selectedMonth) {
		this.selectedMonth = selectedMonth;
	}

	public String getJakarta() {
		return jakarta;
	}

	public void setJakarta(String jakarta) {
		this.jakarta = jakarta;
	}

	public Map<String, String> getAreaMap() {
		return areaMap;
	}

	public void setAreaMap(Map<String, String> areaMap) {
		this.areaMap = areaMap;
	}

	public String[] getYears() {
		return years;
	}

	public void setYears(String[] years) {
		this.years = years;
	}

	public Integer getSelectedYear() {
		return selectedYear;
	}

	public void setSelectedYear(Integer selectedYear) {
		this.selectedYear = selectedYear;
	}

	public List<Report02Model> getReport02Models() {
		return report02Models;
	}

	public void setReport02Models(List<Report02Model> report02Models) {
		this.report02Models = report02Models;
	}

	public Map<String, Object> getParamMap() {
		return paramMap;
	}

	public void setParamMap(Map<String, Object> paramMap) {
		this.paramMap = paramMap;
	}

	public Long getAreaId() {
		return areaId;
	}

	public void setAreaId(Long areaId) {
		this.areaId = areaId;
	}

	@Override
	public void prepare() throws Exception {

		init();
	}
}